﻿using MyNeighbourhood.Helpers;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MyNeighbourhood.Filters
{
    public class InternalExternalAddressAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string ipAddress = HttpContext.Current.Request.UserHostAddress;

            ipAddress = "127.0.0.8";

            if (filterContext.RequestContext.RouteData.Values["controller"].ToString() == "Home" &&
                filterContext.RequestContext.RouteData.Values["action"].ToString() == "Index")
            {
                if (IsIpAddressInternal(ipAddress.Trim()))
                {
                    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary { { "controller", "Home" }, { "action", "InternalIndex" } });
                }
            }
            else if (!IsIpAddressInternal(ipAddress.Trim()))                
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "Forbidden"
                };
            }
        }

        private static bool IsIpAddressInternal(string ipAddress)
        {
            string internalRangeString =
              Convert.ToString(ConfigurationManager.AppSettings["InternalUsersIPs"]);

            string[] internalRange = internalRangeString.Trim().Split(new char[] { '-', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (HelperMethods.IsIpInRange(internalRange[0], internalRange[1], ipAddress))
            {
                return true;
            }

            return false;
        }
    }
}